package br.com.globalcode.framework.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class GenericDao {

	public Connection getConnection() throws ClassNotFoundException,
			SQLException {

		// 1 Registrar o Driver
		Class.forName("org.apache.derby.jdbc.ClientDriver");

		// 2 Representa a conexao com o danado do banco.
		Connection conn = DriverManager.getConnection(
				"jdbc:derby://localhost:1527/clinicafacil" // jdbcurl
				, "user" // user
				, "app" // password
		);

		return conn;

	}

	public int executePreparedUpdate(Connection conn, String sql,
			Object... parameters) throws SQLException {
		PreparedStatement pstmt = conn.prepareStatement(sql);
		int result = 0;
		try {
			int i = 0;
			for (Object parameter : parameters) {
				pstmt.setObject(++i, parameter);
			}
		
			result = pstmt.executeUpdate();
		} finally {
			
			release(pstmt);
		}
			
		return result; 
	
	}	

	public int executePreparedUpdate(String sql
							        , Object... parameters) 
									throws ClassNotFoundException,
											SQLException {
		Connection conn = getConnection();
		int result = 0;
		try {
			result = executePreparedUpdate(conn, sql, parameters);
		} finally {
			release(conn);
		}

		return result;
	}

	public void release(Connection conn) {
		if (conn == null) return; 				
		try {
			conn.close();
		} catch (SQLException e) {
		}
	}
	
	public void release(Statement stmt) {
		if (stmt == null) return; 				
		try {
			stmt.close();
		} catch (SQLException e) {
		}
	}
	
	public void release(ResultSet rset) {
		if (rset == null) return; 				
		try {
			rset.close();
		} catch (SQLException e) {
		}
	}
	
	public void release(Statement stmt, ResultSet rset) {
		release(rset);
		release(stmt);
	}
	
	public void release(Connection conn
					  , Statement stmt
					  , ResultSet rset) {
		release(stmt,rset);
		release(conn);
	}
		
	public int executeUpdate(Connection conn, String sql) throws SQLException {
		Statement stmt = conn.createStatement();
		return stmt.executeUpdate(sql);
	}

	public int executeUpdate(String sql) throws ClassNotFoundException,
			SQLException {
		Connection conn = getConnection();
		return executeUpdate(conn, sql);

	}

	public ResultSet executeQuery(Connection conn, String sql)
			throws SQLException {
		Statement stmt = conn.createStatement();
		return stmt.executeQuery(sql);
	}

	public ResultSet executeQuery(String sql) throws ClassNotFoundException,
			SQLException {
		Connection conn = getConnection();
		return executeQuery(conn, sql);

	}

}
